package com.butterfly.service;


import com.butterfly.domain.dao.PointConfigurationDAO;
import com.butterfly.domain.dao.UserPointCaptureDAO;
import com.butterfly.domain.entity.PointAccumulationType;
import com.butterfly.domain.entity.PointConfiguration;
import com.butterfly.domain.entity.UserPointCapture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Named;
import java.util.Date;

@Named
@Transactional(readOnly = true)
public final class UserPointCaptureServiceImpl implements UserPointCaptureService {

    @Autowired
    private PointConfigurationDAO pointConfigurationDAO;

    @Autowired
    private UserPointCaptureDAO userPointCaptureDAO;


    static final String SYSTEM_USER = "system";

    @Override
    public void addPoint(int userId, int merchantAdId, PointAccumulationType pointAccumulationType) {
        PointConfiguration pointConfig = pointConfigurationDAO.getPointConfig(pointAccumulationType.getPointParameter().getCode());
        UserPointCapture userPointCapture = userPointCaptureDAO.getUserPoint(userId);

        UserPointCapture accumulatedPointCapture = new UserPointCapture();
        accumulatedPointCapture.setPointAccumulationType(pointAccumulationType);
        accumulatedPointCapture.setUserId(userId);
        accumulatedPointCapture.setMerchantAdId(merchantAdId);
        accumulatedPointCapture.setPointUser(Integer.parseInt(pointConfig.getValue()));

        int accPoint = Integer.parseInt(pointConfig.getValue()) + userPointCapture.getCurrentPointUser();
        accumulatedPointCapture.setCurrentPointUser(accPoint);
        accumulatedPointCapture.setLastUpdatedBy(SYSTEM_USER);
        accumulatedPointCapture.setLastUpdatedDate(new Date());

        userPointCaptureDAO.save(accumulatedPointCapture);
    }

    @Override
    public int getUserPoint(int userId) {
        UserPointCapture userPointCapture = userPointCaptureDAO.getUserPoint(userId);
        return userPointCapture.getCurrentPointUser();
    }
}
